<?php

namespace App\Models\System;

use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;

class TestLocation extends Model implements Sortable
{
	use HasDateTimeFormatter;
    use SoftDeletes;

    use SortableTrait;

    protected $table = 'test_locations';

    protected $guarded = [];

    protected $sortable = [
        'order_column_name' => 'order',
        'sort_when_creating' => true,
    ];

    public function creator() : BelongsTo
    {
        return $this->belongsTo(Administrator::class, 'creator_id');
    }

    public function getDistance($lat1, $lon1)
    {
        $lat2 = $this->latitude;
        $lon2 = $this->longitude;
        if (! $lat2 || !$lon2) {
            return 9999999;
        }
        $earthRadius = 6371; // 地球平均半径，单位为千米
        $lat1 = deg2rad($lat1);
        $lon1 = deg2rad($lon1);
        $lat2 = deg2rad($lat2);
        $lon2 = deg2rad($lon2);
        $deltaLat = $lat2 - $lat1;
        $deltaLon = $lon2 - $lon1;
        $a = sin($deltaLat / 2) * sin($deltaLat / 2) + cos($lat1) * cos($lat2) * sin($deltaLon / 2) * sin($deltaLon / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        $distance = $earthRadius * $c;
        return $distance;
    }
}
